package com.maxd.controller.taobao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.CommonInfo;
import com.maxd.model.Req;
import com.maxd.model.UserInfo;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.utils.Config;
import com.maxd.utils.HttpClientUtil;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(value = "淘宝api管理", tags = {"淘宝api管理"})
@Slf4j
@RequestMapping(value = "/taobao")
public class TaoController {

    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ApiOperation("全网淘客商品查询API")
    @IgnoreSecurity
    @ResponseBody
    public String list(int page,int size,@ApiParam("排序 1降序，2升序，3销量，0-，" +
            "5累计推广量，6总支出佣金，7价格") int sort,@ApiParam("搜索商品名称")String keyword) {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo tbName = commonRepository.findOne(11);
        CommonInfo pid = commonRepository.findOne(9);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",String.valueOf(appkey.getValue()));
        map.put("pid",String.valueOf(pid.getValue()));
        map.put("tbname",String.valueOf(tbName.getValue()));
        map.put("pagesize",String.valueOf(size));
        map.put("pageno",String.valueOf(page));
        map.put("sort",getSort(sort));
        map.put("keyword",keyword);
        String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/getTkMaterialItem", map);
        return body;
    }

    //排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate），
    // 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price）
    private String getSort(int sort){
        switch (sort){
            case 1:
                return "des";
            case 2:
                return "asc";
            case 3:
                return "total_sales";
            case 4:
                return "tk_rate";
            case 5:
                return "tk_total_sales";
            case 6:
                return "tk_total_commi";
            case 7:
                return "price";
            default:
                return "total_sales";
        }
    }


    @RequestMapping(value = "/doItemHighCommissionPromotionLink", method = RequestMethod.GET)
    @ApiOperation("高佣转链接API(商品ID)")
    @ResponseBody
    public String doItemHighCommissionPromotionLink(@ApiParam("宝贝ID") String itemid) {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo tbName = commonRepository.findOne(11);
        CommonInfo pid = commonRepository.findOne(9);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",String.valueOf(appkey.getValue()));
        map.put("pid",String.valueOf(pid.getValue()));
        map.put("tbname",String.valueOf(tbName.getValue()));
        map.put("itemid",String.valueOf(itemid));
        String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/doItemHighCommissionPromotionLink", map);
        return body;
    }

    @RequestMapping(value = "/doItemHighCommissionPromotionLinkByTpwd", method = RequestMethod.GET)
    @ApiOperation("高佣转链接API(淘口令)")
    @ResponseBody
    public String doItemHighCommissionPromotionLinkByTpwd(@ApiParam("任意淘口令") String tpwdcode) {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo tbName = commonRepository.findOne(11);
        CommonInfo pid = commonRepository.findOne(9);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",String.valueOf(appkey.getValue()));
        map.put("pid",String.valueOf(pid.getValue()));
        map.put("tbname",String.valueOf(tbName.getValue()));
        map.put("tpwdcode",String.valueOf(tpwdcode));
        String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/doItemHighCommissionPromotionLink", map);
        return body;
    }


    @RequestMapping(value = "/doItemHighCommissionPromotionLinkByAll", method = RequestMethod.GET)
    @ApiOperation("万能高佣转链API接口")
    @ResponseBody
    public String doItemHighCommissionPromotionLinkByAll(@ApiParam("口令/链接等内容") String content) {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo tbName = commonRepository.findOne(11);
        CommonInfo pid = commonRepository.findOne(9);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",String.valueOf(appkey.getValue()));
        map.put("pid",String.valueOf(pid.getValue()));
        map.put("tbname",String.valueOf(tbName.getValue()));
        map.put("content",String.valueOf(content));
        String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/doItemHighCommissionPromotionLinkByAll", map);
        return body;
    }

    @RequestMapping(value = "/createTaoPwd", method = RequestMethod.GET)
    @ApiOperation("淘口令生成API")
    @ResponseBody
    public String createTaoPwd(@ApiParam("淘口令链接") String url,@ApiParam("淘口令弹窗文字，不能少于5个字符") String title) {
        CommonInfo appkey = commonRepository.findOne(30);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",String.valueOf(appkey.getValue()));
        map.put("url",url);
        map.put("title",title);
        String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/createTaoPwd", map);
        return body;
    }

    @RequestMapping(value = "/doTpwdCovert", method = RequestMethod.GET)
    @ApiOperation("淘口令解析&转链")
    @ResponseBody
    public String createTaoPwd(@ApiParam("带淘口令的内容") String content) {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo tbName = commonRepository.findOne(11);
        CommonInfo pid = commonRepository.findOne(9);
        Map<String,String> map=new HashMap<>();
        map.put("apkey",String.valueOf(appkey.getValue()));
        map.put("pid",String.valueOf(pid.getValue()));
        map.put("tbname",String.valueOf(tbName.getValue()));
        map.put("content",String.valueOf(content));
        String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/doTpwdCovert", map);
        return body;
    }



    @RequestMapping(value = "/tbwd", method = RequestMethod.POST)
    @ApiOperation("用户端获取淘口令的api")
    @ResponseBody
    public String getTbwd(@RequestBody Req req1) {
        try {
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", req1.getAppKey(), req1.getAppSecret());
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.setText(req1.getText());
            req.setUrl(req1.getUrl());
            req.setLogo(req1.getLogo());
            TbkTpwdCreateResponse rsp = client.execute(req);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }

//    @RequestMapping(value = "/tbwd/convert", method = RequestMethod.POST)
//    @ApiOperation("解析淘口令")
//    @ResponseBody
//    public String convertTkl(@RequestBody Req req1) {
//        try {
//             //获取淘宝的appkey
//            CommonInfo one = commonRepository.findOne(6);
//            //获取淘宝的秘钥
//            CommonInfo two = commonRepository.findOne(7);
//            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
//            TbkTpwdConvertRequest req = new TbkTpwdConvertRequest();
//            req.setPasswordContent("￥2k12308DjviP￥");
//            req.setAdzoneId(12312312L);
//            req.setDx("1");
//            TbkTpwdConvertResponse rsp = client.execute(req);
//            return rsp.getBody();
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    /**
     * 获取邀请码
     *
     * @param token https://mos.m.taobao.com/inviter/register?inviterCode=HHH49S&src=pub&app=common
     * @return
     */
    @RequestMapping(value = "/invitecode/{token}", method = RequestMethod.POST)
    @ApiOperation("用户端获取邀请码的api")
    @ResponseBody
    public String getInviteCode(@PathVariable String token) {

        try {
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkScInvitecodeGetRequest req = new TbkScInvitecodeGetRequest();
            req.setRelationId(11L);
            req.setRelationApp("common");
            req.setCodeType(1L);
            TbkScInvitecodeGetResponse rsp = client.execute(req, token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取思域用户信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/publisherInfo/token/{token}", method = RequestMethod.POST)
    @ApiOperation("用户端获取私域用户信息")
    @ResponseBody
    public String getPublisher(@RequestBody TbkScPublisherInfoGetRequest request, @PathVariable String token) {
        try {
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkScPublisherInfoGetRequest req = new TbkScPublisherInfoGetRequest();
            req.setInfoType(request.getInfoType());
            req.setRelationId(request.getRelationId());
            req.setPageNo(1L);
            req.setPageSize(request.getPageSize());
            req.setRelationApp("common");
            req.setSpecialId(request.getSpecialId());
            TbkScPublisherInfoGetResponse rsp = client.execute(req, token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }


    @GetMapping("/getRelationIdByUserId")
    @ApiOperation("通过用户id查询是否授权淘宝")
    @ResponseBody
    public Result getRelationIdByUserId(Long userId) {
        UserInfo userById = userRepository.getUserById(userId);
        try {
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            //获取session
            CommonInfo session = commonRepository.findOne(131);
            TaobaoClient client = new DefaultTaobaoClient("https://eco.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkScPublisherInfoGetRequest req = new TbkScPublisherInfoGetRequest();
            req.setInfoType(1L);
            req.setPageNo(1L);
            req.setPageNo(100L);
            req.setRelationApp("common");
            TbkScPublisherInfoGetResponse rsp = client.execute(req,session.getValue());
            String body = rsp.getBody();
            log.error("用户淘宝授权返回值："+body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONObject error_response = jsonObject.getJSONObject("error_response");
            if(error_response!=null){
                String sub_msg = error_response.getString("sub_msg");
                return ResultUtil.error(-200,sub_msg);
            }
            JSONObject tbk_sc_publisher_info_get_response = jsonObject.getJSONObject("tbk_sc_publisher_info_get_response");
            JSONObject data = tbk_sc_publisher_info_get_response.getJSONObject("data");
            JSONObject inviter_list = data.getJSONObject("inviter_list");
            JSONArray map_data = inviter_list.getJSONArray("map_data");
            if(map_data!=null && map_data.size()>0){
                for(int i=0;i<map_data.size();i++){
                    JSONObject jsonObject1 = map_data.getJSONObject(i);
                    String rtag = jsonObject1.getString("rtag");
                    if(org.apache.commons.lang.StringUtils.isNotEmpty(rtag)){
                        if(String.valueOf(userById.getId()).equals(rtag)){
                            userById.setRelationId(jsonObject1.getString("relation_id"));
                            userJpaRepository.save(userById);
                            return ResultUtil.success();
                        }
                    }
                }
            }
        } catch (ApiException e) {
            log.error(e.getErrCode()+"-----"+e.getErrMsg());
            e.printStackTrace();
        }
        return ResultUtil.error(-200,"查询失败，请稍后再试！");
    }

    @GetMapping("/getTwd")
    @ApiOperation("生成用户授权淘口令")
    @ResponseBody
    public Result getTwd(Long userId) {
        try {
            //获取淘宝的appkey
            CommonInfo appkey = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo secret = commonRepository.findOne(7);
            //获取邀请码
            CommonInfo invitation = commonRepository.findOne(15);
            TaobaoClient client = new DefaultTaobaoClient("https://eco.taobao.com/router/rest", appkey.getValue(), secret.getValue());
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.setUrl("https://mos.m.taobao.com/inviter/register?inviterCode="+invitation.getValue()+"&src=pub&app=common&rtag="+userId);
            req.setText("复制打开TB授权");
            TbkTpwdCreateResponse response = client.execute(req);
            return ResultUtil.success(response.getBody());
        } catch (ApiException e) {
            log.error(e.getErrCode()+"-----"+e.getErrMsg());
            e.printStackTrace();
        }
        return ResultUtil.error(-200,"查询失败，请稍后再试！");
    }




    /**
     * 保存用户的信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/savePublisher/{token}", method = RequestMethod.GET)
    @ApiOperation("用户端保存私域用户信息")
    @ResponseBody
    public String savePublisher(@PathVariable String token) {
        try {
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            //获取淘宝私域邀请码
            CommonInfo three = commonRepository.findOne(15);
            //获取全局名称
            CommonInfo four = commonRepository.findOne(12);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
            req.setRelationFrom("1");
            req.setOfflineScene("4");
            req.setOnlineScene("3");
            req.setInviterCode(three.getValue() != null ? three.getValue() : Config.InviterCode);
            req.setInfoType(1L);
            req.setNote(four.getValue() != null ? four.getValue() : Config.BASE_NAME);
            TbkScPublisherInfoSaveResponse rsp = client.execute(req, token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 保存用户的信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/saveAppPublisher/{token}", method = RequestMethod.GET)
    @ApiOperation("APP用户端保存私域用户信息")
    @ResponseBody
    public String saveAppPublisher(@PathVariable String token) {
        try {
            //获取淘宝私域邀请码
            CommonInfo three = commonRepository.findOne(15);
            //获取全局名称
            CommonInfo four = commonRepository.findOne(12);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "27748674", "ace11fae2f3ec7965a46ee19c731dc3f");
            TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
            req.setRelationFrom("1");
            req.setOfflineScene("4");
            req.setOnlineScene("3");
            req.setInviterCode(three.getValue() != null ? three.getValue() : Config.InviterCode);
            req.setInfoType(1L);
            req.setNote(four.getValue() != null ? four.getValue() : Config.BASE_NAME);
            TbkScPublisherInfoSaveResponse rsp = client.execute(req, token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 保存用户的信息
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "/savePublisherCode/{token}/{code}", method = RequestMethod.GET)
    @ApiOperation("用户端保存用户的信息")
    @ResponseBody
    public String savePublisherCode(@PathVariable String token, @PathVariable String code) {
        try {
            //获取全局名称
            CommonInfo four = commonRepository.findOne(12);
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkScPublisherInfoSaveRequest req = new TbkScPublisherInfoSaveRequest();
            req.setRelationFrom("1");
            req.setOfflineScene("4");
            req.setOnlineScene("3");
            req.setInviterCode(code);
            req.setInfoType(1L);
            req.setNote(four.getValue() != null ? four.getValue() : Config.BASE_NAME);
            TbkScPublisherInfoSaveResponse rsp = client.execute(req, token);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }


    @RequestMapping(value = "/auth/{code}", method = RequestMethod.GET)
    @ApiOperation("手机APP通过code获取淘宝的token")
    @ResponseBody
    public String taoBaoAppAuth(@PathVariable String code) {
        try {
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "27742632", "f1343d7d317fe05f57055a352fc1bea7");
            TopAuthTokenCreateRequest req = new TopAuthTokenCreateRequest();
            req.setCode(code);
            TopAuthTokenCreateResponse rsp = client.execute(req);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 用户已经退款的订单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/refund", method = RequestMethod.POST)
    @ApiOperation("未使用 用户已经退款的订单")
    @ResponseBody
    public String getRefund(@RequestBody TbkRelationRefundRequest.TopApiRefundRptOption request) {
        try {
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkRelationRefundRequest req = new TbkRelationRefundRequest();
            TbkRelationRefundRequest.TopApiRefundRptOption obj1 = new TbkRelationRefundRequest.TopApiRefundRptOption();
            obj1.setPageSize(request.getPageSize());
            obj1.setSearchType(request.getSearchType());
            obj1.setRefundType(request.getRefundType());
            obj1.setStartTime(request.getStartTime());
            obj1.setPageNo(request.getPageNo());
            obj1.setBizType(request.getBizType());
            req.setSearchOption(obj1);
            TbkRelationRefundResponse rsp = client.execute(req);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 获取订单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/dgPublisherOrder", method = RequestMethod.POST)
    @ApiOperation("未使用 获取订单")
    @ResponseBody
    public String tbkDgPunishOrderGetRequest(@RequestBody TbkDgPunishOrderGetRequest.TopApiAfOrderOption request) {
        try {
            //获取淘宝的appkey
            CommonInfo one = commonRepository.findOne(6);
            //获取淘宝的秘钥
            CommonInfo two = commonRepository.findOne(7);
            TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);
            TbkDgPunishOrderGetRequest req = new TbkDgPunishOrderGetRequest();
            TbkDgPunishOrderGetRequest.TopApiAfOrderOption obj1 = new TbkDgPunishOrderGetRequest.TopApiAfOrderOption();
            obj1.setSpan(request.getSpan());
            obj1.setRelationId(request.getRelationId());
            obj1.setTbTradeId(request.getTbTradeId());
            obj1.setTbTradeParentId(request.getTbTradeParentId());
            obj1.setPageSize(request.getPageSize());
            obj1.setPageNo(request.getPageNo());
            obj1.setStartTime(request.getStartTime());
            obj1.setSpecialId(request.getSpecialId());
            obj1.setViolationType(request.getViolationType());
            obj1.setPunishStatus(request.getPunishStatus());
            req.setAfOrderOption(obj1);
            TbkDgPunishOrderGetResponse rsp = client.execute(req);
            return rsp.getBody();
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return "";
    }



    /**
     * 淘礼金创建
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/tljCreate", method = RequestMethod.GET)
    @ApiOperation("淘礼金创建")
    @ResponseBody
    public Result tljCreate(Long itemId, Long num, String name, Long winNum, String perFace, String startTime, String endTime){
        //获取淘宝的appkey
        CommonInfo appkey = commonRepository.findOne(6);
        //获取淘宝的秘钥
        CommonInfo secret = commonRepository.findOne(7);
        TaobaoClient client = new DefaultTaobaoClient(Config.url, appkey.getValue(), secret.getValue());
        TbkDgVegasTljCreateRequest req = new TbkDgVegasTljCreateRequest();
        //定向：DX；鹊桥：LINK_EVENT；营销：MKT
        req.setCampaignType("MKT");
        req.setAdzoneId(109264550298L);
        req.setItemId(itemId);
        req.setTotalNum(num);
        req.setName(name);
        req.setUserTotalWinNumLimit(winNum);
        req.setSecuritySwitch(true);
        req.setPerFace(perFace);
        req.setSendStartTime(StringUtils.parseDateTime(startTime));
        req.setSendEndTime(StringUtils.parseDateTime(endTime));
        /*req.setUseEndTime("5");
        req.setUseEndTimeMode(1L);
        req.setUseStartTime("2019-01-29");*/
        TbkDgVegasTljCreateResponse rsp = null;
        try {
            rsp = client.execute(req);
            TbkDgVegasTljCreateResponse.Result result = rsp.getResult();
            return ResultUtil.success(result);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return ResultUtil.success(rsp.getBody());
    }







}
